/**
 * 浦发借记卡抓取
 * @type {boolean}
 */
var isInputFlags = false;
var taskKey="";
var commMap = new HashMap(); //公共信息
var billDay = ""; //每月账单日
var showTimes = 0;
var undoneBill;
var creditCardData;
var debitCardData;
//卡信息列表集合
var depositList=new ArrayList();
var urls = {
    //请求登录页面
    REQ_LOGIN_URL:"https://ebank.spdb.com.cn/nbper/prelogin.do",
    //请求卡列表中间页
    REQ_CARDS_MIDDLE_URL:"https://ebank.spdb.com.cn/nbper/PreQueryHistory.do?_viewReferer=default,account/QueryHistory&selectedMenu=menu1_1_4",
    //请求卡列表信息
    REQ_CARDS_URL:"https://ebank.spdb.com.cn/nbper/",
    // 请求用户卡列表信息
    REQ_USER_INFO_URL:"https://ebank.spdb.com.cn/nbper/DisplayMarketInfo.json",
    //获取借记卡存款信息网址
    REQ_DEDIT_DEPOSIT_URL:"https://ebank.spdb.com.cn/nbper/NewQueryBalance.do",
    //获取借记卡账单信息页
    REQ_DEDIT_BILL_URL:"https://ebank.spdb.com.cn/nbper/QueryHistory.json",
    //借记卡消费记录下载地址
    REQ_DEBIT_DOWLOD_URL:"https://ebank.spdb.com.cn/nbper/DownloadHistory.do",
    // 请求信用卡基本信息 https://ebank.spdb.com.cn/nbper/CreditQueryAcctInfo.do?selectedMenu=menu1_2_1_1&_viewReferer=default
    REQ_CREDIT_CARD_INFO_URL:"https://ebank.spdb.com.cn/nbper/CreditQueryAcctInfo.do?selectedMenu=menu1_2_1_1&_viewReferer=default",
    //请求已出账单页面
    REQ_BILL_URL:"https://ebank.spdb.com.cn/nbper/AccountQueryCreditBill.json",
    //请求未出账单页面
    REQ_UNBILL_URL:"https://ebank.spdb.com.cn/nbper/AccountQueryCreditTrans.json",
}
load("js/luaclient.js")

var v6_spd_java_funcs = {
    openHomePage : function(){
        var loginUrl=urls.REQ_LOGIN_URL;
        get(loginUrl);
        // luaFuncs.waitLoadOk();
        luaFuncs.setSizeAndShow();
        var loginText=luaFuncs.getHtmlGb2312();
        logger.info("浦发-个人网银，任务:{}，打开登录页，",context.get(LUA_TASK_KEY));
        storeDataToFile(context, loginText,  "firstLoginText.html");
        context.put("loginText", loginText);
    },
    checkProxyAvailable: function(){
        var loginText = context.get("loginText");
        return StringUtils.isNotBlank(loginText) && equals(Jsoup.parse(loginText).select(".header").get(0).select("a").get(0).text(),"浦发首页")
    },

    checkTargetWebsiteAvailable:function(){
        return true;
    },
    needResetEnvironment:function(){
        return true;
    },
    checkControlAvailable:function(){
        logger.info("浦发-个人网银，任务:{}，checkControlAvailable 方法，验证控件方法。",context.get(LUA_TASK_KEY));
        return Boolean.valueOf(luaFuncs.checkControlAvailable());
    },
    //登录方法
    login:function () {
        var isValidFlag = false;
        taskKey= context.get(LUA_TASK_KEY);
        luaFuncs.threadSleep();
        luaFuncs.threadSleep();
        logger.info("浦发-个人网银，任务:{}，开始登录",taskKey);
        showTimes = System.nanoTime();   //用来计算窗口show的时间
        var username = getLoginParams(context)[0];
        if(StringUtils.isBlank(username)){
            isValidFlag = false;
            throw new BankException(BankConstants.BALO_22001_10, "用户名或密码错误");
        }
        var isInputLoginId =luaFuncs.input_username(username);
        // var isInputLoginId = set_frame_input_text_by_id("LoginId",username,"login-iframe");
        if(equals(isInputLoginId.toLowerCase(),"ok")){
            isValidFlag = true;
        }

        isValidThorwError(isInputLoginId,isValidFlag,"用户或密码无效");
        logger.info("浦发-个人网银，任务:{}，借记卡号输入成功", taskKey)
        var passwordValue = context.get(LUA_TASK_TOKEN);
        var pwdCheckResult = luaFuncs.loginPassword(passwordValue);
        // var isInputPwd = set_frame_input_text_by_id("LoginId",passwordValue,"login-iframe");
        var isPwdCheck = Boolean.valueOf(pwdCheckResult);
        if(isPwdCheck){
            isValidFlag = true;
        }
        isValidThorwError(pwdCheckResult,isValidFlag,"密码因控件输入错误");
        logger.info("浦发-个人网银，任务:{}，密码输入成功", taskKey);
        //图片验证码判断以及校验
        var check = luaFuncs.if_Exit_ImsCode();
        logger.info("浦发-个人网银，任务:{}，是否需要输入图片验证码：{}，", taskKey,check);
        //noneed 不需要   need  需要
        if("need".equals(check)){
            var captchaPath = get_image_by_id("tokenImg");
            logger.info("浦发-个人网银，任务:{}，图片验证码路径【 {} 】", taskKey, captchaPath)
            if(captchaPath !== null && captchaPath !== undefined && captchaPath !== 'path fail'){
                isValidFlag = true;
            }
            isValidThorwError(captchaPath,isValidFlag,"图片验证码获取失败");
            logger.info("浦发-个人网银，任务:{}，图片验证码获取成功", taskKey)

            //识别图片验证码
            context.put(TASK_IMG_PATH, captchaPath);
            //图片验证码只会是4位，但是由于官网返回经常有看不清的字母所以本处支持3,4位
            context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{6}");
            var captcha = waitImgCodeBySecondsByJs(context,180,true, 3);

            //输入图片验证码
            var isInputVerCodeToken =  set_frame_input_text_by_id("verCodeToken", captcha,"login-iframe");
            //检查验证码是否输入正常
            if(equals(isInputVerCodeToken.toLowerCase(),"ok")){
                isValidFlag = true;
            }
            isValidThorwError(isInputVerCodeToken,isValidFlag,"图片验证码输入错误");
            logger.info("浦发-个人网银，任务:{}，图片验证码输入成功", taskKey)
            context.put(TASK_IMG_PATH, captchaPath);
        }
        showTimes = System.nanoTime() - showTimes;
        logger.info("浦发-个人网银，任务:{}，,窗口显示时间：{}", taskKey, showTimes);
        logger.info("浦发-个人网银，任务:{}，点击登录",taskKey);
        var loginResult = luaFuncs.click_login_button();
        hide();
        // 判断用户是否登录成功
        var doc = Jsoup.parse(loginResult);
        // 获取登录错误原因
        var isLoginMassge = doc.select("#errInfo").text();
        logger.info("浦发-个人网银，任务:{}，页面返回错误信息 isLoginMassge:{}",taskKey,isLoginMassge);
        if(StringUtils.isNotBlank(isLoginMassge)){
            isInputFlags = false;
            if(isLoginMassge.contains("您的账户已被锁定")){
                isLoginMassge = "您的账户已被锁定,请1小时后再试。"
            }
            if(isLoginMassge.contains("EGG0042:内部错误")){
                isLoginMassge = "用户名或密码错误";
            }
            logger.info("浦发-个人网银，任务:{}，报错信息 isLoginMassge:{}",taskKey,isLoginMassge);
            throw new BankException(BankConstants.BALO_22001_10, isLoginMassge);
        }
        var loginAfteriframeHtml = luaFuncs.getHtmlGb2312();
        storeDataToFile(context, loginAfteriframeHtml,  "login_server_deal.html");
        luaFuncs.threadSleep();
        if(loginAfteriframeHtml.contains("理财版首次登录")){
            logger.info("浦发-个人网银，任务:{}，用户首次登录，进入服务协议页面",taskKey);
            // 判断用户是否登录成功
            var loginAfteriString = Jsoup.parse(loginAfteriframeHtml);
            luaFuncs.threadSleep();
            luaFuncs.threadSleep();
            click_by_id("agreementSubmit");
            luaFuncs.threadSleep();
            luaFuncs.threadSleep();
            var agreementText = loginAfteriString.select("agreementSubmit");
            logger.info("浦发-个人网银，任务:{}，agreementText:{}",taskKey,agreementText);
            var login_server_deal_after = luaFuncs.getHtmlGb2312();
            storeDataToFile(context, login_server_deal_after,  "login_server_deal_after.html");
            logger.info("浦发-个人网银，任务:{}，保存login_server_deal_after.html 成功",taskKey);
        }
        if(loginAfteriframeHtml.contains("您已签约我行个人网银动态密码安全认证方式，请尽快完成激活。")){
            // 输入短信验证码
            //等待短信
            var smsCode = waitSmsCodeBySeconds(context, 120);
            logger.info("浦发云账单 taskKey:{} 等待短信结果{}",context.get(LUA_TASK_KEY),smsCode);
            //action开始: 校验短信验证码
            var isSmsCodeCorrectFunc = function(smsCode) {
                return StringUtils.isNotBlank(smsCode) && smsCode.length === 6;
            }
            var getSmsCodeErrorMsgFunc = function() {
                return "短信验证码错误";
            }
            assertTrueOrThrowException(smsCode, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc);
            showTimes =  System.nanoTime() - showTimes;   //用来计算窗口show的时间
            logger.info("浦发云账单 taskKey:{} 开始等待验证短信验证码结束时间{}",context.get(LUA_TASK_KEY),showTimes);
            //输入短信验证码
            set_input_text_by_id("MobilePasswd",smsCode);
            //检查短信验证码是否输入正常
            var smsInputResult = luaFuncs.checkIfInput("MobilePasswd",smsCode);

            var isSmsInputCorrectFunc = function(smsInputResult) {
                return Boolean.valueOf(smsInputResult);
            }

            var getSmsInputErrorMsgFunc = function(smsInputResult) {
                return "短信验证码错误";
            }
            assertTrueOrThrowException(smsInputResult, isSmsInputCorrectFunc, getSmsInputErrorMsgFunc);
            luaFuncs.threadSleep();
            click_by_class("button-lg");// 点击确认按钮
            luaFuncs.threadSleep();
            luaFuncs.threadSleep();
        }
    },
    crawl: crawl,
    exitLogin: function () {
    }

}

function crawl() {
    luaFuncs.closeADButton();
    logger.info("浦发-个人网银，任务:{}，开始抓取，",taskKey);
    luaFuncs.threadSleep();
    luaFuncs.threadSleep();
    screen_print();
    var userInfoUrl = urls.REQ_USER_INFO_URL;
    var paramsMap = new JSONObject();
    var userDetillHtml = luaFuncs.ajaxJsonPost(userInfoUrl,paramsMap.toString());
    storeDataToFile(context, userDetillHtml,  "userDetillHtml.html");
    var userDetill = JSON.parse(userDetillHtml);
    var username = userDetill.get("Name");
    //获取登录用户姓名
    // var username=luaFuncs.Get_username();
    if(username == null && username == ""){
        logger.error("浦发-个人网银，任务:{}，用户名获取失败", taskKey, e);
    }
    // var username=username.replaceAll("先生","").trim();
    //此页面跳转后才能转到借记卡查询页面
    var cardInfo = luaFuncs.ajaxGet(urls.REQ_CARDS_MIDDLE_URL);
    //获取关于解析卡的页面
    var docCardNum = Jsoup.parse(cardInfo);
    storeDataToFile(context, docCardNum,  "sys_card_list_befer.html");
    logger.info("浦发-个人网银，任务:{}，卡列表前置页面保存成功",taskKey);
    var cardNoEles = docCardNum.select(".card-iframe-div iframe");
    var srcVal = cardNoEles.attr("src");
    var debitUrl = urls.REQ_CARDS_URL + srcVal;
    var cardInfoDitail = luaFuncs.ajaxGet(debitUrl);
    storeDataToFile(context, cardInfoDitail,  "sys_card_list.html");
    logger.info("浦发-个人网银，任务:{}，借记卡查询页面已保存",taskKey);
    var cardsHtml = Jsoup.parse(cardInfoDitail);
    /*
     * todo 这个地方需要优化，查出银行卡总数量，
     * 再按照类型查出卡类型，
     * 再根据卡类型进行查询调用抓取，设置变量记录抓取不同卡类型记录数
     */
    var debitDardNnms = cardsHtml.getElementsByAttributeValue("type", "type1");
    var debitDardNnmSize = debitDardNnms.size();
    var creditCardNnms = cardsHtml.getElementsByAttributeValue("type", "type2");
    var creditCardNnmSize = creditCardNnms.size();
    if(debitDardNnmSize > 0 || creditCardNnmSize > 0){
        logger.info("浦发-个人网银，任务:{}，开始抓取。",taskKey);
        //抓取借记卡
        crawlDebitCard(debitDardNnms,username,taskKey);
        //抓取信用卡
        crawlCreditCard(creditCardNnms,username,taskKey);
        context.put("creditCardSize",creditCardNnmSize);
        context.put("debitCardSize",debitDardNnmSize);
        //crawlSecondSys();
        context.put(Constants.ALL_DATA,depositList);
    }else{
        logger.info("浦发-个人网银，任务:{}，银行卡数量为【{}】， 借记卡【{}】张，信用卡【{}】张，",taskKey,debitDardNnmSize + creditCardNnmSize,debitDardNnmSize,creditCardNnmSize);
        throw new BankException(BankConstants.BALO_20304_30, "未获取到卡片信息");
    }
}
function crawlDebitCard(debitDardNnms,username,taskKey) {
    var debitDardNnmSize = debitDardNnms.size();
    logger.info("浦发-个人网银，任务:{}， 借记卡【{}】张。",taskKey,debitDardNnmSize);
    for(var debitIndex = 0;debitIndex<debitDardNnmSize;debitIndex++){
        logger.info("浦发-个人网银，任务:{}，开始抓取第 {} 张借记卡",taskKey,(debitIndex+1));
        var elements = debitDardNnms.get(debitIndex).siblingElements();
//        System.out.println("卡类型：" + elements);
        var select = elements.select(".swiper-slide-num-bold");
        var currentCardNo = select.get(0).attr("value");
        commMap.put("AcNo", currentCardNo);
        debitCardData = newCreditCardAllData(currentCardNo,username);
        debitCardData.setCardType("借记卡");
        debitCardData.setBankName("浦发银行");
        debitCardData.setFullCardNum(currentCardNo);
        debitCardData.setCardNum(currentCardNo.substring(currentCardNo.length - 4,currentCardNo.length));
        //保存 存款信息
        var debitUrl = urls.REQ_DEDIT_DEPOSIT_URL;
        //采集借记卡存款信息页
        collectDebitHtml(debitUrl,currentCardNo,debitIndex,taskKey);
        //抓取借记卡存款信息
        addDebitDeposits(debitCardData,currentCardNo,debitIndex,taskKey);
        // 采集借记卡信息页面，返回下载后的借记卡消费信息记录的Excel文件路径
        collectDebitBillsHtml(currentCardNo,debitIndex,taskKey);
        //抓取借记卡账单信息页
        saveBillsInfo(currentCardNo,debitCardData,debitIndex,taskKey);
        //saveBillsInfo(currentCardNo,debitBillsInfo,creditCardData,index);
        depositList.add(debitCardData);
    }
}
function crawlCreditCard(creditCardNnms,username,taskKey){
    var creditCardNnmSize = creditCardNnms.size();
    logger.info("浦发-个人网银，任务:{}， 抓取到信用卡【{}】张。",taskKey,creditCardNnmSize);
    for(var crebitIndex = 0;crebitIndex<creditCardNnmSize;crebitIndex++){
        logger.info("浦发-个人网银，任务:{}，开始抓取第 {} 张信用卡",taskKey,(crebitIndex+1));
        var elements = creditCardNnms.get(crebitIndex).siblingElements();
//        System.out.println("卡类型：" + elements);
        var select = elements.select(".swiper-slide-num-bold");
        var currentCardNo = select.get(0).attr("value");
        commMap.put("AcNo", currentCardNo);
        creditCardData = newCreditCardAllData(currentCardNo,username);
        collectCraditInfo(crebitIndex,currentCardNo);
        saveCraditCardInfo(crebitIndex,creditCardData);
        // 采集信用卡信息
        // collectCardInfoHtml(crebitIndex);
        // saveCardInfo(creditCardAllData);
        //抓取已出账单,能够抓取6个月的数据,
        for(var motheIndex = 1 ;motheIndex<=6;motheIndex++){
            //采集已出账单数据 simpleDateFormatToYear
            var billMonth= simpleDateFormatToYear(motheIndex-1,"yyyyMM","M");//循环获取查询月份
            collectDoneBillsHtml(currentCardNo,billMonth,crebitIndex,taskKey);
            //抓取已出账单数据
            saveBasicInfoCredit(currentCardNo,creditCardData,billMonth,crebitIndex,taskKey);
        }
        var mother= simpleDateFormatToYear(0,"yyyyMM","M",taskKey);//未出账单一般为当月
        //采集未出账单页
        collectUnDoneBillsHtml(currentCardNo,mother,crebitIndex,taskKey);
        //未出账单
        saveUndoneBillsCredit(currentCardNo,creditCardData,mother,crebitIndex,taskKey);
        depositList.add(creditCardData);
    }
}

/**
 * 创建卡信息对象
 * @param currentCardNo
 * @param username
 * @returns {CreditCardAllData}
 */
function newCreditCardAllData(currentCardNo,username) {
    var creditCardAllData = new CreditCardAllData();
    if(currentCardNo==null){
        logger.error("浦发-个人网银，任务:{}，抓取银行卡失败.",taskKey);
    }
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    //卡号后四位
    creditCardAllData.setCardNum(currentCardNo.substring(currentCardNo.length()-4, currentCardNo.length()));//卡号后四位
    creditCardAllData.setFullCardNum(currentCardNo);//完整卡号
    creditCardAllData.setNameOnCard(username);//持卡人
    //账单列表
    creditCardAllData.setBills(new ArrayList());

    //存款信息
    creditCardAllData.setDeposits(new ArrayList());
    creditCardAllData.setCashBalance(null);
    creditCardAllData.setCashLimit(null);
    creditCardAllData.setCreditLimit(null);
    return creditCardAllData;
}

/**
 *
 */
function collectCraditInfo(crebitIndex,creditAcctno) {
    var craditCardInfoUrl = "https://ebank.spdb.com.cn/nbper/QueryCreditCanUseBalance.json";
    var paramsMap = new JSONObject();
    paramsMap.put("_SysTokenName","P95W6C");
    paramsMap.put("_viewReferer","default,account/QueryBalance");
    paramsMap.put("chooseType","bankcard");
    paramsMap.put("CreditAcctno",creditAcctno);
    paramsMap.put("hasInvest","1");
    paramsMap.put("isFinancHas","0");
    paramsMap.put("isFundHas","0");
    paramsMap.put("onebookNum","0");
    paramsMap.put("ReceiptNum","0");
    var cardBalanceInfo = luaFuncs.ajaxJsonPost(craditCardInfoUrl,paramsMap.toString());
    storeDataToFile(context, cardBalanceInfo,"信_"+crebitIndex+"_card_balance_info.html");
    context.put(crebitIndex+"_card_balance_info",cardBalanceInfo);
    logger.info("浦发-个人网银，任务:{}， 采集信用卡总消费信息，结束，",taskKey);

}

/**
 * 采集借记卡存款页面
 * @param url
 */
function collectDebitHtml(url,currentCardNo,debitIndex,taskKey) {
    logger.info("浦发-个人网银，任务:{}， 采集借记卡存款页面，开始，",taskKey);
    //获取卡信息,余额,开户银行
    var cardBalanceUrlInfo = urls.REQ_DEDIT_DEPOSIT_URL;
    //请求参数
    var paramsMap = new HashMap();
    paramsMap.put("_viewReferer","default,account/NewQueryBalanceRes");
    paramsMap.put("_tokenName","p52trm");
    paramsMap.put("selectedMenu","menu1_1_1_1_1_1");
    paramsMap.put("selectedSubMenu","menu1_1_1_1_1_1_1");
    paramsMap.put("AcctType","1");
    paramsMap.put("CurrencyNo","");
    paramsMap.put("CurrencyType","");
    paramsMap.put("SelectFlag","");
    paramsMap.put("AcctNo",currentCardNo);
    var sendParams = changeMap2FormData(paramsMap);
    var cardBalanceInfo = luaFuncs.ajaxPost(cardBalanceUrlInfo,sendParams);
    storeDataToFile(context, cardBalanceInfo,"借"+debitIndex+"_card_balance_list.html");
    logger.info("浦发-个人网银，任务:{}， 采集借记卡存款页面，结束，",taskKey);
    context.put("借"+debitIndex+"_card_balance_list",cardBalanceInfo)
}
/**
 * 采集用户账单信息页，这个方法中是指查询后获取下载文集0
 * 返回下载后的借记卡消费信息记录的Excel文件路径
 * @param url
 */
function collectDebitBillsHtml(currentCardNo,debitIndex,taskKey){
    //采集借记卡账单信息页
    // REQ_DEDIT_BILL_URL ************是下一个请求的前置请求
    var debitBillUrl = urls.REQ_DEDIT_BILL_URL;
    var beginDate = simpleDateFormatToYear(2 ,"yyyyMMdd","y");
    var endDate = simpleDateFormatToYear(0 ,"yyyyMMdd","y");
    var paramsMap = new JSONObject();
    paramsMap.put("SelectFlag", "3");
    paramsMap.put("AcctNo", currentCardNo);
    paramsMap.put("BeginDate", beginDate);
    paramsMap.put("EndDate", endDate);
    paramsMap.put("CurrencyNo", "01");
    paramsMap.put("CurrencyType", "0");
    paramsMap.put("LoanStatus", "2");
    paramsMap.put("BeginNumber", "1");
    //发送ajax请求
    var historyData = luaFuncs.ajaxJsonPost(debitBillUrl,paramsMap.toString());
    storeDataToFile(context, historyData,"借"+debitIndex+"_card_bills_list.html");
    // REQ_DEDIT_BILL_URL************
    var historyDataJson =  JSON.parse(historyData);
    var errmsg = historyDataJson.get("errmsg");
    logger.info("浦发-个人网银，任务:{}，借记卡账单查询,查询交易记录提示信息errmsg:{}", taskKey, errmsg);
    var filePath = "";
    if(StringUtils.isBlank(errmsg)) {
        //下载文件并解析
        var downloadUrl = urls.REQ_DEBIT_DOWLOD_URL + "?AcctNo=" + currentCardNo + "&BeginDate=" + beginDate + "&EndDate=" + endDate + "&CurrencyType=0&AcctKind=0001&CurrencyNo=01"
        //把路径转换成String类型
        filePath = luaFuncs.ajaxDownload(downloadUrl);
        var copyFilePath = filePathToLocal(context, filePath, "借_" + debitIndex + "_excel_list.xlsx",taskKey);
        context.put(debitIndex + "_filePath",copyFilePath);
        // var filePath = luaFuncs.ajaxDownloadFile(downloadUrl);
        logger.info("浦发-个人网银，任务:{}，借记卡账单查询,下载文件的路径为:{}", taskKey, filePath);
    }else{
        filePath = "";
        logger.info("浦发-个人网银，任务:{}，借记卡账单查询,下载文件异常，异常信息为:{}", taskKey, errmsg);
        context.put("filePath",filePath);
    }
}

/**
 * 采集信用卡
 */
function collectCardInfoHtml(crebitIndex) {
    logger.info("浦发-个人网银，任务:{}，采集 第 {} 信用卡基本信息，开始",taskKey,crebitIndex + 1);
    var cardInfoURL = urls.REQ_CREDIT_CARD_INFO_URL;
    var cardInfoHtml = luaFuncs.ajaxGet(cardInfoURL);
    storeDataToFile(context, cardInfoHtml,  "信_"+crebitIndex+"_card_info.html");
    context.put("cardInfoDetail",cardInfoHtml);
    logger.info("浦发-个人网银，任务:{}，采集 第 {} 信用卡基本信息，结束",taskKey,crebitIndex + 1);
}
/**
 * 采集信用卡已出账单页面
 * @param url
 */
function collectDoneBillsHtml(currentCardNo,mother,crebitIndex,taskKey) {
    var doneUrl = urls.REQ_BILL_URL;
    logger.info("浦发-个人网银，任务:{}，采集信用卡第 {} 已出账单页面，开始",taskKey,mother);
    //请求参数
    var paramsMap = new JSONObject();
    paramsMap.put("_viewReferer", "default,account/AccountQueryCreditBill");//当前月份
    paramsMap.put("SelectedBillMonth", mother);//当前月份
    paramsMap.put("CurrencyType", "L");
    paramsMap.put("CreditAcctno", currentCardNo);
    paramsMap.put("selectedMenu", "menu1_1_5_1_1_1");
    paramsMap.put("selectedSubMenu", "menu1_1_5_1_1_1_1");
    paramsMap.put("AccountType", "个人信用卡");
    paramsMap.put("BillMonth", mother);
    paramsMap.put("creditBillMonth", mother);
    var SendData = paramsMap.toString();
    var doneBillsData = luaFuncs.ajaxJsonPost(doneUrl,SendData);
    context.put("信_"+crebitIndex+"_DONE_"+mother+"_bills",doneBillsData)
    /**注意：这个地方需要把月份格式进行转换 201808 转 2018-08*/
    // mother = yyyy_MM_PARSER.format(mother);// TODO 这个地方可能会有问题
    storeDataToFile(context, doneBillsData,  "信_"+crebitIndex+"_DONE_"+mother+"_bills.html");
    logger.info("浦发-个人网银，任务:{}，采集信用卡已出账单页面，结束，",taskKey);
}
/**
 * 采集信用卡未出账单页面
 * @param url
 */
function collectUnDoneBillsHtml(currentCardNo,mother,index,taskKey) {
    logger.info("浦发-个人网银，任务:{}，采集信用卡未出账单页面，开始，",taskKey);
    var unDoneUrl = urls.REQ_UNBILL_URL;
    //请求参数
    var paramsMap = new JSONObject();
    paramsMap.put("_viewReferer", "default,account/AccountQueryCreditTrans");//当前月份
    paramsMap.put("SelectedBillMonth", mother);//当前月份
    paramsMap.put("CurrencyType", "L");
    paramsMap.put("CreditAcctno", currentCardNo);
    paramsMap.put("selectedMenu", "menu1_1_5_1_1_1");
    paramsMap.put("selectedSubMenu", "menu1_1_5_1_1_1_2");
    paramsMap.put("AccountType", "个人信用卡");
    var SendData = paramsMap.toString();
    var unDoneBillsData = luaFuncs.ajaxJsonPost(unDoneUrl,SendData);
    logger.info("浦发-个人网银，任务:{}，获取信用卡信息，{}",taskKey,unDoneBillsData);
    /**注意：这个地方需要把月份格式进行转换 201808 转 2018-08*/
    // mother = getDateStr(mother, "yyyyMM"), "yyyy-MM");
    context.put("信_"+index+"_UNDONE_"+mother+"_bills",unDoneBillsData)
    storeDataToFile(context, unDoneBillsData,  "信_"+index+"_UNDONE_"+mother+"_bills.html");
    logger.info("浦发-个人网银，任务:{}，采集信用卡未出账单页面，结束，",taskKey);
}

/**
 * 保存信用卡基本信息
 * @param creditCardAllData
 */
function saveCardInfo(creditCardAllData) {
    var cardInfoDetail = context.get("cardInfoDetail");
    try {
        if(cardInfoDetail != undefined){
            if(cardInfoDetail.contains("return is null")){
                logger.info("浦发-个人网银，任务:{}，未抓取到信用卡基本信息，{}",taskKey,cardInfoDetail);
            }else{
                var cardDetail = Jsoup.parse(cardInfoDetail);
                var cardDetailTable = cardDetail.select(".table");
                var tableElemensInfo = cardDetailTable.get(0).getElementsByTag("td");
                var creditLimit = tableElemensInfo.get(2).text().replaceAll(",","");// 信用卡额度balance
                var balance = tableElemensInfo.get(4).text().replaceAll(",","");// 信用卡可用额度
                var cashBalance = tableElemensInfo.get(6).text().replaceAll(",","");// 现金额度
                billDay = tableElemensInfo.get(8).text();// 账单日
                creditCardAllData.setCardId(UUID.randomUUID().toString());
                creditCardAllData.setBankName("浦发银行");
                creditCardAllData.setCardType("信用卡");
                creditCardAllData.setCreditLimit(stringToBigDecimal(creditLimit));//信用额度
                creditCardAllData.setBalance(stringToBigDecimal(balance));// 信用卡可用额度
                creditCardAllData.setCashLimit(stringToBigDecimal(cashBalance));// 现金额度
                creditCardAllData.setCashBalance(stringToBigDecimal(cashBalance));// 现金可用额度
            }
        }
    }catch (e) {
        logger.info("浦发-个人网银，任务:{}，抓取信用卡信息出错，{}",taskKey,e);
    }
}
/**
 * 保存信用卡基本信息
 * @param creditCardAllData
 */
function saveCraditCardInfo(crebitIndex,creditCardAllData) {
    var cardBalanceInfo = context.get(crebitIndex + "_card_balance_info");
    try {
        //{"BalanceUSD":"0.00","AvailableAmt":"121307.60","IsMessage":"yes","_TransactionId":"QueryCreditCanUseBalance","ResponseCode":"AAAAAAA","Balance":"2692.40","ResponseMsg":null,"CreditLimit":"124000.00"}
        if(cardBalanceInfo != undefined){
            if(cardBalanceInfo.contains("return is null")){
                logger.info("浦发-个人网银，任务:{}，未抓取到信用卡基本信息，{}",taskKey,cardBalanceInfo);
            }else{
                var cardBalanceInfoJson = JSON.parse(cardBalanceInfo);
                var responseCode = cardBalanceInfoJson.get("ResponseCode");
                if ("AAAAAAA" == responseCode){
                    var creditLimit = cardBalanceInfoJson.get("CreditLimit");// 信用卡额度balance
                    var balance = cardBalanceInfoJson.get("AvailableAmt");// 信用卡可用额度
                    // var cashBalance = tableElemensInfo.get(6).text().replaceAll(",","");// 现金额度
                    // billDay = tableElemensInfo.get(8).text();// 账单日
                    creditCardAllData.setCardId(UUID.randomUUID().toString());
                    creditCardAllData.setBankName("浦发银行");
                    creditCardAllData.setCardType("信用卡");
                    creditCardAllData.setCreditLimit(stringToBigDecimal(creditLimit));//信用额度
                    creditCardAllData.setBalance(stringToBigDecimal(balance));// 信用卡可用额度
                }
            }
        }
    }catch (e) {
        logger.info("浦发-个人网银，任务:{}，抓取信用卡信息出错，{}",taskKey,e);
    }
}
/**
 * 获取借记卡存款信息
 * @param creditCardAllData
 * @param currentCardNo
 * @param index
 */
function addDebitDeposits(creditCardAllData,currentCardNo,index,taskKey) {
    logger.info("浦发-个人网银，任务:{}，保存借记卡卡号信息，",taskKey);
    var cardBalanceInfo = context.get("借"+index+"_card_balance_list");
    var balanceInfo = Jsoup.parse(cardBalanceInfo);
    //获取开户银行
    var backOpenCardDate = balanceInfo.select(".col-10").get(0).text();
    var openBank = backOpenCardDate.substring(backOpenCardDate.lastIndexOf(": "));
    if(openBank == null && openBank ==""){
        logger.error("浦发-个人网银，任务:{}，获取浦发借记卡开户银行获取失败,{}",taskKey,e);
    }
    creditCardAllData.setOpenBank(openBank);//设置开户行
    //获取借记卡定期和活期数据
    var selectsTable = balanceInfo.select(".table");
    var sizeCont = selectsTable.size();
    for (var eleIndex = 0 ;eleIndex < sizeCont ;eleIndex++){
        var deposits = new CreditCardTimeDeposit();
        var banElement = selectsTable.get(eleIndex);
        var trEle = banElement.getElementsByTag("tr");
        var trElement = trEle.get(2).getElementsByTag("td");
        var trText = trElement.get(0).text();
        if(trText.contains("活期")){
            deposits.setDepositType("活期");
            deposits.setInterest(null);
            deposits.setPeriod(null);
            var cnyText = trElement.get(1).text();
            if(cnyText.contains("人民币")){
                deposits.setCurrencyType("CNY");
            }else if(cnyText.contains("美元")){
                deposits.setCurrencyType("USD");
            }
            var balanceText = trElement.get(3).text();
            if(null != balanceText && !"".equals(balanceText)){
                balanceText = balanceText.trim().replaceAll(",","");
                deposits.setBalance(stringToBigDecimal(balanceText));
                creditCardAllData.setBalance(stringToBigDecimal(balanceText))//可用余额
            }
            creditCardAllData.getDeposits().add(deposits);    //放入活期对象
            logger.info("浦发-个人网银，任务:{}，借记卡保存存款信息，活期存款保存成功。", taskKey);
        }else if (trText.contains("整存整取")){
            logger.info("浦发-个人网银，任务:{}，借记卡保存存款信息，整存整取开始保存。", taskKey);
            deposits.setDepositType("整存整取");//存款类型
            deposits.setInterest(null);
            deposits.setPeriod(null);
            var cnyText = trElement.get(2).text();//币种
            if(cnyText.contains("人民币")){
                deposits.setCurrencyType("CNY");
            }else if(cnyText.contains("美元")){
                deposits.setCurrencyType("USD");
            }
            var balanceText = trElement.get(4).text();
            if (null != balanceText && !"".equals(balanceText)) {
                balanceText = balanceText.trim().replaceAll(",", "");
                deposits.setBalance(stringToBigDecimal(balanceText));    //金额
                var periodText = trElement.get(5).text();
                deposits.setPeriod(periodExchange(periodText));  //存期
                deposits.setPeriodUnit(periodUnit(periodText)); //存期单位
                var endDate = trElement.get(6).text();  //抓下来的格式 ：2017/09/19
                if (null !== endDate && !"".equals(endDate)) {
                    //string类型
                    var due_date = getDateStr(endDate, "yyyy/MM/dd", "yyyy-MM-dd");
                    //转换成data类型
                    var expireDate = getDate(due_date, "yyyy-MM-dd");
                    //logger.info("抓取的值是{}",expireDate);
                    deposits.setDueDate(expireDate);  //到期日期.格式yyyy-MM-dd
                    //logger.info("打印到期日期{}", expireDate);
                    var depositDate = getDate(getDepositeDate(due_date, periodText), "yyyy-MM-dd");
                    deposits.setDepositDate(depositDate);   //存款日期
                }
            }
            creditCardAllData.getDeposits().add(deposits);    //放入活期对象
            logger.info("浦发-个人网银，任务:{}，借记卡保存存款信息，整存整取存款保存成功。taskKey:{},{}", taskKey);
        }
    }
}

/**
 * 保存交易流水信息----个人网银入口借记卡账单抓取
 * @param currentCardNo
 * @param creditCardData
 * @param index
 */
function saveBillsInfo(currentCardNo,creditCardData,index,taskKey) {
    try {
        var filePath = context.get(index + "_filePath");
        //判断表格路径是否存在
        if (FileUtil.isFile(filePath)) {
            var actTrsInfoRecords = readExcel(filePath);
            //浦发只支持24个月的查询,按照月份为单位
            var mounthList = getBeforTwentyFourMounth();
            logger.info("浦发-个人网银，任务:{}，借记卡，mounthList:{}", taskKey, mounthList);
            var cardInfo = actTrsInfoRecords.get(0).get(1);
            var cardNum =cardInfo.substring(cardInfo.length()-4, cardInfo.length());
            actTrsInfoRecords.remove(0);
            // logger.info("浦发|个人网银 任务【{}】，借记卡，actTrsInfoRecords:{}", taskKey, actTrsInfoRecords);
            for (var mounthListIndex = 0;mounthListIndex<mounthList.size();mounthListIndex++) {
                var mounthSingle = mounthList.get(mounthListIndex);
                var mounthValue = mounthSingle.get("mounthDate");
                var bill_month = getDateStr(mounthValue,"yyyyMMdd","yyyy-MM");
                //logger.info("抓取的数据{}",bill_month);
                var debitBillAllData = new BillAllData();
                creditCardData.getBills().add(debitBillAllData)
                setValueForBill(debitBillAllData);
                debitBillAllData.setBillId(UUID.randomUUID().toString());
                debitBillAllData.setBankName("浦发银行");
                debitBillAllData.setBillMonth(bill_month);
                debitBillAllData.setBillType("");
                debitBillAllData.setBillDate(getDate(bill_month + "-01","yyyy-M-dd"));
                if (currentCardNo.equals(cardInfo)) {
                    var orderIndex = 1;
                    var expenseList = new ArrayList();
                    for (var shoppingIndex = 1; shoppingIndex < actTrsInfoRecords.size(); shoppingIndex++) {
                        var singleExpense = actTrsInfoRecords.get(shoppingIndex);
                        //获取交易日期
                        var trans_day = singleExpense.get(1);
                        var expense = new Expense();
                        // billAllData.setShoppingSheets.add(expense);
                        var sinmple_trans_day = getDateStr(trans_day,"yyyy/MM/dd HH:mm:ss","yyyy-MM-dd HH:mm:ss");
                        // var trans_mounth = getDateStr(singleExpense.get(1), "yyyy/MM/dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
                        var mounth2 = getDateStr(sinmple_trans_day,"yyyy-MM-dd HH:mm:ss","yyyy-MM");
                        if (bill_month.equals(mounth2)) {
                            expense.setId(UUID.randomUUID());
                            expense.setCardNum(cardNum);
                            // var trans_date = getDategetDateStr(singleExpense.get(1), "yyyy/MM/dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
                            // var trans_date1 = TimeUtil.getTime(trans_date, "yyyy-MM-dd HH:mm:ss");
                            // logger.info("表格中打印的数据是{}", trans_date1);
                            expense.setTransDate(getDate(sinmple_trans_day,"yyyy-MM-dd HH:mm:ss"));
                            expense.setPostDate(getDate(sinmple_trans_day,"yyyy-MM-dd HH:mm:ss"));
                            var description = singleExpense.get(2);
                            //logger.info("打印的数据是{}", description);
                            expense.setDescription(description);
                            var save_money = singleExpense.get(3).replaceAll(",", "").trim();  //存入
                            var draw_money = singleExpense.get(4).replaceAll(",", "").trim();  //取出
                            expense.setCategory(classify(description, stringToBigDecimal(save_money)));
                            var balance = singleExpense.get(5);// 余额
                            //logger.info("打印的数据是{}", balance);
                            if (balance.contains(",")) {
                                balance = balance.replaceAll(",", "");
                            }
                            // 消费为正 存入为负
                            var amount_money = "0.00";
                            if(StringUtils.isNotBlank(save_money)){
                                amount_money = "-" +save_money;
                            }else if(StringUtils.isBlank(save_money)){
                                amount_money = draw_money;
                            }
                            expense.setAmountMoney(stringToBigDecimal(amount_money));
                            expense.setBalance(stringToBigDecimal(balance));
                            expense.setOrderIndex(orderIndex++);
                            expense.setCurrencyType("CNY");
                            expenseList.add(expense);
                        }
                    }
                    debitBillAllData.setShoppingSheets(expenseList);
                }
            }
            logger.info("浦发-个人网银，任务:{}，借记卡：【{}】账单抓取结束",taskKey);
        }else{
            logger.info("浦发-个人网银，任务:{}，借记卡：【{}】没有消费账单",taskKey);
        }
    }catch (e) {
        logger.error("浦发-个人网银，任务:{}，抓取借记卡，在 saveBillsInfo 方法中保存交易流水信息时出错,{}", taskKey, e);
    }
}

/**
 * 抓取已出账单数据
 * @param currentCardNo
 * @param creditCardAllData
 * @param billMonth
 * @param index
 * @param taskKey
 */
function saveBasicInfoCredit(currentCardNo,creditCardAllData,billMonth,index,taskKey){
    try {
        var doneBillsData = context.get("信_"+index+"_DONE_"+billMonth+"_bills");
        var doneBillMap =  JSON.parse(doneBillsData);
        if(equals("",billDay)){
            billDay = doneBillMap.get("BillDate");
            commMap.put("BillDate",billDay);
        }
        logger.error("浦发-个人网银，任务:{}，信用卡已出账单， doneBillMap:{}",taskKey,doneBillMap);
        // commMap.put("BillDay",billDay);
        var responseCode = doneBillMap.get("ResponseCode");//相应信息
        var doneBillData = new BillAllData();
        doneBillData.setBillType("DONE");
        doneBillData.setBankName("浦发银行");
        doneBillData.setBillId(UUID.randomUUID().toString());
        //美元相关
        setValueForBillUSDCredit(doneBillData);
        //yyyy_MM_dd_PARSER.parse(replaceAll(billDate_json,"/", "-"))
        if(equals("AAAAAAA",responseCode)){
            // 获取该月账单日
            var billDateTime = billMonth + doneBillMap.get("BillDate");
            billDateTime = getDateStr(billDateTime,"yyyyMMdd","yyyy-MM-dd");
            doneBillData.setBillDate(getDate(billDateTime,"yyyy-MM-dd"));
            doneBillData.setBillMonth(getDateStr(billMonth, "yyyyMM", "yyyy-MM"));
            doneBillData.setCreditLimit(stringToBigDecimal(doneBillMap.get("PermCreditLimit")));       //信用卡额度
            doneBillData.setCashLimit(stringToBigDecimal(doneBillMap.get("SecondCurrencyCreditLimit")));       //预借现金额度
            doneBillData.setPaymentDueDate(getDate(doneBillMap.get("PaymentDueDay"),"yyyyMMdd"));  //到期还款日
            doneBillData.setNewBalance(stringToBigDecimal(doneBillMap.get("BillAmount")));   // CurrentNeedPayAmt 本期账单金额
            doneBillData.setMinPayment(stringToBigDecimal(doneBillMap.get("MinAmountDue"))); //最低还款额
            //"BillAmount": "732.55",
            doneBillData.setLastBalance(null); //上期账单金额
            // var last_payment = String.valueOf(doneBillMap.get("AlreadyPayAmt"));
            doneBillData.setLastPayment(stringToBigDecimal(doneBillMap.get("AlreadyPayAmt")));  //上期还款金额
            doneBillData.setNewCharges(stringToBigDecimal(doneBillMap.get("BillAmount")));   //本期新增款额
            //账单详情
            doneBillData.setShoppingSheets(new ArrayList());
            //获取用户消费信息
            var customerList =  doneBillMap.get("LoopResult");
            if(null !== customerList && customerList.size() > 0){
                var installmentList = new ArrayList();
                // storeDataToFile(context, customerList,  "信"+index+"_bill_"+billMonth+"_shopping_sheets_.html");
                for (var fieldNum = 0;fieldNum<customerList.size();fieldNum++) {
                    var expenseObj = customerList.get(fieldNum);
                    getExpenseCredit(doneBillData,expenseObj,fieldNum,taskKey,installmentList);
                    // doneBillData.getShoppingSheets().add(expense);
                }
                manageInstallmentList(installmentList);
                doneBillData.setInstallments(installmentList);
            }
            creditCardAllData.getBills().add(doneBillData);
        }else{
            logger.info("浦发-个人网银，任务:{}，信用卡已出账单  该月{}月无该账户的账单记录，doneBillMap：{}",taskKey,billMonth,doneBillMap);
        }
    }catch (e) {
        logger.error("浦发-个人网银，任务:{}，信用卡保存基本信息时出错, e:{}",taskKey, e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 *
 * @param currentCardNo
 * @param undonMap
 * @param creditCardAllData
 * @param billMonth
 * @param index
 * @param taskKey
 */
function saveUndoneBillsCredit(currentCardNo,creditCardAllData,billMonth,index,taskKey) {
    var unDoneBillsData = context.get("信_"+index+"_UNDONE_"+billMonth+"_bills")
    if(StringUtils.isBlank(unDoneBillsData)){
        logger.info("浦发银行信用卡未出账单  未找到符合条件的记录，taskKey:{}", taskKey);
    }else{
        var undonBillMap =  JSON.parse(unDoneBillsData);
        var responseCode = undonBillMap.get("ResponseCode");
        if(!equals("AAAAAAA",responseCode)){
            logger.info("浦发银行信用卡未出账单  无该账户的账单记录，taskKey:{},页面信息：{}",taskKey,responseCode);
        }else{
            //var unBillDay = commMap.get("BillDay");
            logger.info("浦发银行信用卡未出账单记录，taskKey:{},页面信息：{}",taskKey,undonBillMap);
            var undoneBillList =  undonBillMap.get("LoopResult");
            var billAllData = new BillAllData();
            billAllData.setBillType("UNDONE");
            billAllData.setBankName("浦发银行");
            billAllData.setBillId(UUID.randomUUID().toString());
            //美元相关
            setValueForBillUSDCredit(billAllData);
            billAllData.setBillMonth(getDateStr(billMonth, "yyyyMM", "yyyy-MM"));
            billAllData.setBillDate(getDate(billMonth + billDay, "yyyyMMdd"));
            var last_payment = String.valueOf(undonBillMap.get("CreditAmount"));
            billAllData.setLastPayment(null);  //上期还款金额
            billAllData.setNewBalance(stringToBigDecimal(undonBillMap.get("DebitAmount")));   //本期新增款额
            billAllData.setNewCharges(stringToBigDecimal(last_payment));//本期新增款额
            billAllData.setLastBalance(stringToBigDecimal("0"));
            billAllData.setLastPayment(stringToBigDecimal("0"));
            if(null !== undoneBillList && undoneBillList.size() > 0) {
                var installmentList = new ArrayList();
                for (var unIndex = 0; unIndex < undoneBillList.size(); unIndex++) {
                    var undoneBillSinglent = undoneBillList.get(unIndex);
                    getExpenseCredit(billAllData,undoneBillSinglent,unIndex,taskKey,installmentList);
                }
                manageInstallmentList(installmentList);
                // 分期中的手续费
                billAllData.setInstallments(installmentList);
            }

            creditCardAllData.getBills().add(billAllData);
        }
    }
}
/**
 * 账单详情中摘取出分期数据
 * @param expense
 * @param billAllData
 */
function getInstallmentsFromExpense(expense, billAllData,taskKey) {
    try {
        var remark = expense.getDescription();
        //&& (remark.contains("分期") ||remark.contains("支付网关分") || remark.contains("万用金"))
        if (null !== remark && !equals("", remark) && remark.contains("第") && remark.contains("共") && remark.contains("期") && checkIfContainsNum(remark)) {
            //账单分期 每月分摊本金 (第6期共6期)   账单分期 每月分摊本金 &#40;第3期共6期
            //账单分期 手续费 &#40;第3期共6期      分期付款手续费 支付网关分24期 (第23期共24期)
            logger.info("taskKey:{}  remark = {} ", taskKey, remark);
            var remarkStr1 = remark.substring(remark.indexOf("第")); //第3期共6期
            logger.info("taskKey:{}  remarkStr1 = {} ", taskKey, remarkStr1);
            var current_month = remarkStr1.substring(remarkStr1.indexOf("第") + 1, remarkStr1.indexOf("期"));
            if (current_month.contains("第")) {
                logger.info("taskKey:{}  current_month = {} ", taskKey, current_month);
                current_month = current_month.substring(current_month.indexOf("第") + 1);
            }
            var remarkStr2 = remark.substring(remark.indexOf("共"));
            logger.info("taskKey:{}  remarkStr2 = {} ", taskKey, remarkStr2);
            var total_month = remarkStr2.substring(remarkStr2.indexOf("共") + 1, remarkStr2.indexOf("期"));
            var insList = billAllData.getInstallments();
            var ins = null;
            for each(var singleIns in insList){
                var desc = singleIns.getInstallmentDesc();
                var feeDesc = singleIns.getHandingfeeDesc();
                if ((!equals("", desc) && (null !== desc))|| (!equals("", feeDesc) && (null !== feeDesc))) {
                    if (!equals("", feeDesc) && (null !== feeDesc )) {
                        desc = feeDesc;
                    }
                    logger.info("taskKey:{}  desc = {} ", taskKey, desc);
                    var sameDesc = equals(desc.substring(0, 3), remark.substring(0, 3));
                    var desc1 = desc.substring(0, 2);
                    var desc2 = remark.substring(0, 2);
                    var condition = false;
                    if ((equals("每月", desc1) && equals("利息", desc2)) || (equals("每月", desc2) && equals("利息", desc1))) {
                        condition = true;
                    }
                    if (current_month == singleIns.getCurrentMonth() && total_month == singleIns.getTotalMonth() && (sameDesc || condition)) {
                        ins = singleIns;
                    }
                }
            }
            if (null == ins) {
                ins = new Installment();
                ins.setBillId(UUID.randomUUID().toString());
                ins.setHandingFee(null);
                ins.setTransferFee(null);
                billAllData.getInstallments().add(ins);
            }
            //remark.contains("本金")||(remark.contains("支付网关分") && remark.contains("手续费")==false)
            if (remark.contains("手续费") == false && remark.contains("利息") == false) {
                ins.setShoppingsheetId(expense.getId());
                ins.setTransDate(expense.getTransDate());
                ins.setPostDate(expense.getPostDate());
                var installment_type = "";
                if (remark.contains("账单")) {
                    installment_type = "BILL";
                } else if (remark.contains("自由")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("自动")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("现金") || remark.contains("万用金")) {
                    installment_type = "CASH";
                } else {
                    installment_type = "CONSUME";
                }
                ins.setInstallmentType(installment_type);
                ins.setCurrentMonth(current_month);
                ins.setTotalMonth(total_month);
                ins.setCurrencyType(expense.getCurrencyType());
                ins.setAmountMoney(expense.getAmountMoney());
                ins.setInstallmentDesc(remark);

            } else if (remark.contains("手续费") || remark.contains("利息")) {
                var installment_type = "";
                if (remark.contains("账单")) {
                    installment_type = "BILL";
                } else if (remark.contains("自由")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("自动")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("现金") || remark.contains("万用金")) {
                    installment_type = "CASH";
                } else {
                    installment_type = "CONSUME";
                }
                ins.setInstallmentType(installment_type);
                ins.setHandingFee(expense.getAmountMoney()); //本期手续费
                ins.setHandingfeeDesc(remark); //分期手续费描述
                ins.setCurrentMonth(current_month);
                ins.setTotalMonth(total_month);
                ins.setCurrencyType(expense.getCurrencyType());
            }
        }
    } catch (e) {
        logger.error("浦发云账单 taskKey :{} getInstallmentsFromExpense 发生异常:{} ", taskKey, e)
        statCaughtExceptionByJS(context, e);
    }
}
/**
 * 调用验证错误提示公用方法
 * @param isValidFlag
 * @param errorDec
 * @param teskKey
 */
function isValidThorwError(result,isValidFlag, errorDec) {

    var isSmsCodeCorrectFunc = function(isValidFlag) {
        return isValidFlag;
    }

    var getSmsCodeErrorMsgFunc = function(isValidFlag) {
        return errorDec;
    }
    assertTrueOrThrowException(result, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc);
}

/**
 * 读取excel
 *
 * @throws IOException
 * @throws FileNotFoundException
 */
function readExcel(excelFilePath) {
    try {
        var reader1 = ExcelUtil.getReader(FileUtil.file(excelFilePath), 0);
        var read = reader1.read();
        // System.out.println(read);
        return read;
    }catch (e) {
        logger.error();
    }

}
/**
 * 根据抓取到的到期日，和存期推算出存款日
 * @param due_date
 * @param period
 * @return
 */
function getDepositeDate(due_date, period) {
    var calendar = new GregorianCalendar();
    var deposite_date = "";
    try {
        var date = DateUtil.parse(due_date,"yyyy-MM-dd");
        calendar.setTime(date);   //将字符串类型的日期先转换成Date类型再转换成Calendar类型   得到的calender即为转换结果

        if (period.equals("三个月")) {
            calendar.add(Calendar.MONTH, -3);  //月份减三
        } else if (period.equals("六个月")) {
            calendar.add(Calendar.MONTH, -6);
        } else if (period.equals("一年")) {
            calendar.add(Calendar.YEAR, -1);
        } else if (period.equals("二年")) {
            calendar.add(Calendar.YEAR, -2);
        } else if (period.equals("三年")) {
            calendar.add(Calendar.YEAR, -3);
        } else if (period.equals("五年")) {
            calendar.add(Calendar.YEAR, -5);
        }
        var depositeDate = calendar.getTime();
        deposite_date = DateUtil.format(depositeDate,"yyyy-MM-dd");

    } catch (e) {
        e.printStackTrace();
    }

    return deposite_date;
}
/**
 * 获取该日期前后几年的日期
 * @param date  默认是当前时间
 * @param intYear
 */
function simpleDateFormatToYear(intYear,formatType,yearOrMothe) {
    var simpleDateFormat = new SimpleDateFormat(formatType);
    var calendar = Calendar.getInstance();
    var nowDate = calendar.getTime();
    if(equals("y",yearOrMothe)){
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - intYear);
        nowDate =simpleDateFormat.format(calendar.getTime());
        logger.info("{浦发银行借记卡账单查询，获取今天的时间，{}",nowDate);
    }else if(equals("M",yearOrMothe)){
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - intYear);
        nowDate =simpleDateFormat.format(calendar.getTime());
        logger.info("{浦发银行借记卡账单查询，获取{}月的时间，",nowDate);
    }
    return nowDate;
}
/**
 * 复制文件到指定目录
 * @param context
 * @param oldFile
 * @param fileName
 */
function filePathToLocal(context,oldFile,fileName,taskKey) {
    try {
        var year = taskKey.substring(0, 2);
        var month = taskKey.substring(2, 4);
        var day = taskKey.substring(4, 6);
        var filePath = PropertyManager.getRB("htmlStorage", "home_path") +"\\" +"BANK" + "\\" +
            year + "\\" + month + "\\"  + day + "\\" + taskKey + "\\" + fileName;
        logger.info("浦发借记卡，filePath:{}", filePath);
        FileUtils.copyFile(new File(oldFile),new File(filePath));
        return filePath.toString();
    }catch (e) {
        statCaughtExceptionByJS(context, e);
        logger.error("浦发借记卡，在filePathToLocal 方法中保存交易流水信息时出错，taskKey:{},{}", taskKey, e);
    }
}
function getBeforTwentyFourMounth(){
    var calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    // calendar.add(Calendar.YEAR,-2);
    var simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    var list = new ArrayList();
    for (var i = 0; i < 24; i ++) {
        var map = new HashMap();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        var mounthDate = simpleDateFormat.format(calendar.getTime());
        map.put("mounthDate", mounthDate);
        list.add(map);
        calendar.add(Calendar.MONTH, -1);
    }
    return list;
}
/**
 *
 * @param billAllData
 */
function setValueForBill(billAllData) {
    billAllData.setPaymentDueDate(null);
    billAllData.setNewBalance(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setMinPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setLastBalance(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setCreditLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
}
/**
 * 与美元相关
 * @param billAllData
 */
function setValueForBillUSDCredit(billAllData){
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdCashLimit(null);
}
/**
 * 消费信息  -- 信用卡
 *
 */
function getExpenseCredit(billAllData,expenseObj,orderIndex,taskKey,installmentList) {
    var transAmount = stringToBigDecimal("0");
    var expense = new Expense();
    billAllData.getShoppingSheets().add(expense);
    try {
        expense.setNameOnOppositeCard("");
        expense.setOppositeBank("");
        expense.setOppositeCardNo("");
        expense.setRemark("");
        expense.setTransAddr("");
        expense.setTransChannel("");
        expense.setTransMethod("");
        var transDesc1 = expenseObj.get("TransDesc1");
        var transDesc2 = expenseObj.get("TransDesc2");
        var description = transDesc1;//交易描述
        if(transDesc2 != null && transDesc2 != ""){
            description =  description + "_" + transDesc2;
        }
        // var description = expenseObj.get("TransDesc1")+"-"+ expenseObj.get("TransDesc2");  //交易描述
        var uuid = UUID.randomUUID().toString()
        expense.setId(uuid);
        expense.setCardNum(expenseObj.get("Last4AcctNo"));  //卡号后四位
        var consumeDate = expenseObj.get("ConsumeDate");//交易日期
        var bookedDate = expenseObj.get("BookedDate");//记账日期currencyType
        expense.setTransDate(DateUtil.parse(consumeDate,"yyyyMMdd"));
        expense.setPostDate(DateUtil.parse(bookedDate,"yyyyMMdd"));    //记账日期  格式为yyyy-MM-dd

        var sign = expenseObj.get("TransAmountSign");
        var amountMoney = "0";
        if(sign.equals("-")){
            amountMoney = "-" + expenseObj.get("TransAmount");   //消费金额
        }else {
            amountMoney = expenseObj.get("TransAmount");
        }
        amountMoney = stringToBigDecimal(amountMoney);
        // if("01" == expenseObj.get("CurrencyType")){
        //     expense.setCurrencyType("CNY");   //币种
        // }else{
        //     expense.setCurrencyType(null);
        // }
        expense.setCurrencyType("CNY");   //币种
        expense.setAmountMoney(amountMoney);
        expense.setDescription(description==null ? "" : description.replace(" ", ""));  //交易描述
        expense.setCategory(classify(description, amountMoney));
        // expense.setCategory(CategoryUtil.getCreditCategory("COMM", description, expense.getAmountMoney().toString()));
        expense.setOrderIndex(orderIndex + 1);
        expense.setBalance(null);
        //处理账单分期数据
        if(description.contains("分期")){
            var installment = new Installment();
            // bill.getInstallments().add(installment);
            installment.setBillId(UUID.randomUUID().toString());
            installment.setAmountMoney(expense.getAmountMoney());
            installment.setCurrencyType(expense.getCurrencyType());
            installment.setInstallmentDesc(description);
            installment.setShoppingsheetId(uuid);
            //installment.setTransDate(expense.getTransDate());
            if(description.contains("第") && description.contains("期共")){
                //installment.setTransDate(expense.getTransDate());
                var descText = description.substring(description.indexOf("第"),description.length());
                var current_month = descText.substring(descText.indexOf("第") + 1, descText.indexOf("期"));
                var total_month = descText.substring(descText.indexOf("共") + 1, descText.lastIndexOf("期"));
                var transDate = getTimeMonthToNumMonth(Integer.toString(current_month),consumeDate);
                installment.setTransDate(transDate);
                var purDates = getTimeMonthToNumMonth(0,bookedDate);//记账日期
                installment.setPostDate(purDates);
                installment.setInstallmentType(installmentTypeChange(description));
                //这里需要对description进行截取，当description包含现金分期，以前的方法会报错
                installment.setCurrentMonth(current_month);//当前期数
                installment.setTotalMonth(total_month);//总共期数
            }
            installmentList.add(installment);
        }
        if(description.contains("还款")){
            var transAmt = stringToBigDecimal("0");
            if(sign.equals("-")){
                transAmt = stringToBigDecimal("-" + expenseObj.get("TransAmount"));
            }else{
                transAmt = stringToBigDecimal(expenseObj.get("TransAmount"));
            }
            transAmount.add(transAmt);
            billAllData.setLastBalance(transAmount.abs());
            billAllData.setLastPayment(transAmount);
        }
    } catch (e) {
        logger.error("浦发银行消费信息详情解析时出错，taskKey:{}，orderIndex:{},e:{}", taskKey,orderIndex, e);
        statCaughtExceptionByJS(context, e);

    }
    return expense;
}
/**
 * 拼接请求参数
 * @param postdata
 * @returns {string}
 */
function changeMap2FormData(postdata) {
    var sb = new StringBuffer();
    for each(var key  in postdata.keySet()){
        sb.append(key + "=" + postdata.get(key) + "&");
    }
    var data = "";
    if (sb.length() > 0) {
        data = sb.substring(0, sb.length() - 1);
    }
    return data;
}

/**
 *
 * @param period
 * @returns {string}
 */
function periodUnit(period) {
    var data = "";
    if (period.contains("月")) {
        data = "MONTH";
    } else if (period.contains("年")) {
        data = "YEAR";
    } else if (period.contains("天")) {
        data = "DAY";
    }
    return data;
}
/**
 *
 * @param period
 * @returns {number}
 */
function periodExchange(period) {
    var data = 0;
    switch (period) {
        case "三个月":
            data = 3;
            break;
        case "六个月":
            data = 6;
            break;
        case "一年":
            data = 1;
            break;
        case "二年":
            data = 2;
            break;
        case "三年":
            data = 3;
            break;
        case "五年":
            data = 5;
            break;
        case "七天":
            data = 7;
            break;
        default:
            break;
    }
    return data;
}
function read2003Excel(file)  {
    var list = new LinkedList();
    var hwb = new HSSFWorkbook(new FileInputStream(file));
    var sheet = hwb.getSheetAt(0);
    var value = null;
    var row = null;
    var cell = null;
    var counter = 0;
    for (var i = sheet.getFirstRowNum(); counter < sheet.getPhysicalNumberOfRows(); i++) {
        row = sheet.getRow(i);
        if (row == null) {
            continue;
        } else {
            counter++;
        }
        var linked = new LinkedList();
        for (var j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
            cell = row.getCell(j);
            if (cell == null) {
                linked.add("");
            } else {
                linked.add(cell.toString());
            }

        }
        list.add(linked);
    }
    return list;
}
/**
 *  获取前后N各月的当天时间
 * @param num 前后几个月
 * @param time 需要转换的时间
 * @returns {*}
 */
function getTimeMonthToNumMonth(num, time) {
    var calendar=Calendar.getInstance()
    var df=new SimpleDateFormat("yyyyMMdd");
    var years = time.substring(0,4);
    var month = time.substring(4,6);
    var day = time.substring(6,8);
    calendar.set(years, month, day);
    calendar.set(Calendar.MONTH,month-1-num);//默认1月为0月
    var nowTime = calendar.getTime();
    // logger.info("浦发云账单,的记账日期为：{}",df.format(nowTime));
    return nowTime;
}

/**
 * 管理分期，把手续费或息费合并到分期账单中
 * @param installmentList
 */
function manageInstallmentList(installmentList) {
    // 遍历分期数据
    for(var insIndex = 0 ;insIndex < installmentList.size();insIndex++){
        var insInfo = installmentList.get(insIndex);
        var insInfoDesc = insInfo.getInstallmentDesc();
        if(insInfoDesc.contains("息费") || insInfoDesc.contains("手续费")){
            if(installmentList.size() > 0){
                for(var installIndex = 0;installIndex < installmentList.size();installIndex++){
                    var installInfo = installmentList.get(installIndex);
                    var installment_desc = installInfo.getInstallmentDesc();
                    var installmentDescText = installment_desc.substring(installment_desc.indexOf("第"),installment_desc.length());
                    // var install_currentMonth = installInfo.getCurrentMonth();
                    if (insInfoDesc.contains(installmentDescText)){
                        installInfo.setHandingfeeDesc(insInfoDesc);
                        installInfo.setHandingFee(insInfo.getAmountMoney());
                    }
                }
            }
            installmentList.remove(insIndex);
        }
    }
}
/**
 * 判断页面渲染状态
 * @returns {boolean}
 */
function isExist() {
    var exist = is_exist_by_id("menu2");
    logger.info("浦发银行页面渲染加载状态：{}，taskKey:{}",exist,  context.get(Constants.LUA_TASK_KEY));
    return exist;
}
var luaFuncs = {
    /**
     * 获取当前地址
     * @returns {*}
     */
    getURL:function () {
        var map = new LinkedHashMap();
        map.put("method", "getURL");
        return sendAndReceive(map);
    },
    /**
     * GET请求
     * @param url
     * @returns {*}
     */
    ajaxGet: function (url) {
        var map = new LinkedHashMap();
        map.put("method", "ajaxGet");
        map.put("url", url);
        return sendAndReceive(map);
    },
    /**
     * POST请求
     * @param url
     * @param data
     * @returns {*}
     */
    ajaxPost: function (url, data) {
        var map = new LinkedHashMap();
        map.put("method", "ajaxPost");
        map.put("url", url);
        map.put("data", data);
        return sendAndReceive(map);
    },
    /**
     * POST请求，json格式
     * @param url
     * @param data
     * @returns {*}
     */
    ajaxJsonPost: function (url, data) {
        var map = new LinkedHashMap();
        map.put("method", "ajaxJsonPost");
        map.put("url", url);
        map.put("data", data);
        return sendAndReceive(map);
    },
    /**
     * 以Gb2312编码格式获得当前页面
     * @return
     */
    getHtmlGb2312: function () {
        var map = new LinkedHashMap();
        map.put("method", "getHtmlGb2312");
        return sendAndReceive(map);
    },
    input_username: function (text) {
        var map = new HashMap();
        map.put("method", "input_username");
        map.put("text", text);
        return sendAndReceive(map);
    },
    /**
     * 新的输入密码方法（823）
     * @param password
     * @return
     */
    loginPassword: function (password) {
        var map = new HashMap();
        map.put("method", "loginPassword");
        map.put("password", password);
        return sendAndReceive(map);
    },
    /**
     * 获取用户名
     * @returns {*}
     * @constructor
     */
    Get_username: function () {
        var map = new LinkedHashMap();
        map.put("method", "Get_username");
        return sendAndReceive(map);
    },
    /**
     * 截图,然后将当前页面保存到文件
     *
     * @param id
     * @return
     */
    screen_print:function  () {
        var map = new LinkedHashMap();
        map.put("method", "screen_print");
        return sendAndReceive(map);
    },
    /**
     *置前窗口
     * @return
     */
    setSizeAndShow: function () {
        var map = new LinkedHashMap();
        map.put("method", "setSizeAndShow");
        return sendAndReceive(map);
    },
    checkControlAvailable:function(){
        var map = new HashMap();
        map.put("method","checkControlAvailable");
        return sendAndReceive(map)
    },
    if_Exit_ImsCode: function () {
        var map = new HashMap();
        map.put("method", "if_Exit_ImsCode");
        return sendAndReceive(map);
    },
    click_login_button: function () {
        var map = new LinkedHashMap();
        map.put("method", "click_login_button");
        return sendAndReceive(map);
    },
    /**
     * 关闭登录之后的页面广告
     */
    closeADButton: function () {
        var map = new LinkedHashMap();
        map.put("method", "closeADButton");
        return sendAndReceive(map);
    },
    ajaxDownload :function (url) {
        var map = new LinkedHashMap();
        map.put("method", "ajaxDownload");
        map.put("url", url);
        return sendAndReceive(map);
    },
    threadSleep : function(){
        var map = new LinkedHashMap();
        map.put("method", "threadSleep");
        return sendAndReceive(map);
    },
}
